package com.xu.mall.framework.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.xu.mall.framework.model.PageContext;

/**
 * 分类拦截器，通过struts拦截注入查询的页码，每页记录数
 * 
 * @version Revision History
 * 
 *          <pre>
 * Author     Version       Date        Changes
 * lunan.xu   1.0           2012-12-8  Created
 * </pre>
 * 
 * @since 1.
 */
public class PageInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = -3481198345032974574L;

	@Override
	public String intercept(ActionInvocation invoke) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		int startIndex = 0;
		int pageSize = PageContext.DEFAULT_PAGE_SIZE;
		String sortField = "";
		String sortType = "";
		try {
			startIndex = Integer.parseInt(request.getParameter("pager.startIndex"));
			pageSize = Integer.parseInt(request.getParameter("pager.pageSize"));
			sortField = String.valueOf(request.getParameter("sortField"));
			sortType = String.valueOf(request.getParameter("sortType"));
		} catch (Exception e) {
		}

		//将相关的分页数据设置好之后放到Threadlocal中 ，在后台进行查询的时候取出即可。   
		PageContext.setStartIndex(startIndex);
		PageContext.setPageSize(pageSize);
		PageContext.setSortField(sortField);
		PageContext.setSortType(sortType);
		try {
			return invoke.invoke();
		} finally {
			//注意等到整个拦截器执行完成即一个ThreadLocal完成它的工作后要清除里面的内容   
			PageContext.removePageSize();
			PageContext.removeSortField();
			PageContext.removeSortType();
			PageContext.removeStartIndex();
		}
	}
}
